<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function limitLoad(urls, handler, limit) {
        const data = []; // 存储所有的加载结果
        let p = Promise.resolve();
        const handleUrls = (urls) => {
          // 这个函数是为了生成3个url为一组的二维数组
          const doubleDim = [];
          const len = Math.ceil(urls.length / limit); // Math.ceil(8 / 3) = 3
          console.log(len); // 3, 表示二维数组的长度为3
          for (let i = 0; i < len; i++) {
            doubleDim.push(urls.slice(i * limit, (i + 1) * limit));
          }
          return doubleDim;
        };
        const ajaxImage = (urlCollect) => {
          // 将一组字符串url 转换为一个加载图片的数组
          console.log(urlCollect);
          return urlCollect.map((url) => handler(url));
        };
        const doubleDim = handleUrls(urls); // 得到3个url为一组的二维数组
        doubleDim.forEach((urlCollect) => {
          p = p
            .then(() => Promise.all(ajaxImage(urlCollect)))
            .then((res) => {
              data.push(...res); // 将每次的结果展开，并存储到data中 (res为：[img, img, img])
              return data;
            });
        });
        return p;
      }
      limitLoad(urls, loadImg, 3).then((res) => {
        console.log(res); // 最终得到的是长度为8的img数组: [img, img, img, ...]
        res.forEach((img) => {
          document.body.appendChild(img);
        });
      });
    </script>
  </body>
</html>
